﻿using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;

namespace CRL.Data.DBExtend
{
	public class BatchUpdateItem
	{
		internal Dictionary<string, object> condition = new Dictionary<string, object>();
		internal Dictionary<string, object> updateValue = new Dictionary<string, object>();
		public BatchUpdateItem AddCondition(string field, object value)
		{
			condition.Add(field, value);
			return this;
		}
		public BatchUpdateItem AddUpdateValue(string field, object value)
		{
			if (updateValue.ContainsKey(field))
			{
				updateValue[field] = value;
			}
			else
			{
				updateValue.Add(field, value);
			}
			return this;
		}
	}
	public class BatchUpdateItem<T> : BatchUpdateItem
	{
		T _item;
		public BatchUpdateItem()
		{
		}
		public BatchUpdateItem(T item)
		{
			_item = item;
		}
		public BatchUpdateItem<T> AddCondition<TResult>(Expression<Func<T, TResult>> field)
		{
			_item.CheckNull("BatchUpdateItem(T item)");
			var mExp = field.Body as MemberExpression;
			var name = mExp.Member.Name;
			var pro = typeof(T).GetProperty(name);
			var value = pro.GetValue(_item);
			AddCondition(name, value);
			return this;
		}
		public BatchUpdateItem<T> AddCondition<TResult>(Expression<Func<T, TResult>> field, TResult value)
		{
			var mExp = field.Body as MemberExpression;
			var name = mExp.Member.Name;
			AddCondition(name, value);
			return this;
		}

		public BatchUpdateItem<T> AddUpdateValue<TResult>(Expression<Func<T, TResult>> field)
		{
			_item.CheckNull("BatchUpdateItem(T item)");
			var mExp = field.Body as MemberExpression;
			var name = mExp.Member.Name;
			var pro = typeof(T).GetProperty(name);
			var value = pro.GetValue(_item);
			AddUpdateValue(name, value);
			return this;
		}
		public BatchUpdateItem<T> AddUpdateValue<TResult>(Expression<Func<T, TResult>> field, TResult value)
		{
			var mExp = field.Body as MemberExpression;
			var name = mExp.Member.Name;
			AddUpdateValue(name, value);
			return this;
		}
	}

	public class BatchUpdate<T>
	{
		internal List<BatchUpdateItem<T>> items;
		public BatchUpdate()
		{
			items = new List<BatchUpdateItem<T>>();
		}
		public BatchUpdateItem<T> CreateItem()
		{
			var item = new BatchUpdateItem<T>();
			items.Add(item);
			return item;
		}
	}
}
